package me.xiaosiqi.web.controller.store;

import me.xiaosiqi.domain.store.QuestionItem;
import me.xiaosiqi.utils.BeanUtil;
import me.xiaosiqi.utils.FileUtil;
import me.xiaosiqi.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author xiaosiqi
 * @date 2021/6/3 18:01
 */

@WebServlet("/store/questionItem")
public class QuestionItemServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/javascript;charset=utf-8");
        String operation = req.getParameter("operation");
        System.out.println(operation);
        if ("list".equals(operation)){
            // uri:/store/questionItem?operation=list
            try {
                list(req,resp,null);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else if ("delete".equals(operation)){
            // uri:/store/questionItem?operation=delete
            try {
                delete(req,resp);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else if ("saveOrEdit".equals(operation)){
            try {
                saveOrEdit(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toEdit".equals(operation)){
            try {
                toEdit(req,resp);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
    }



    private void list(HttpServletRequest req, HttpServletResponse resp,String questionId ) throws ServletException, IOException, FileUploadException {
        if (questionId==null){
            questionId = req.getParameter("questionId");
        }
        //获取当前题目id 的所有选项
        List<QuestionItem> questionItems = questionItemService.findByQuestionId(questionId);
        //将所有选项写到页面
        req.setAttribute("questionItems",questionItems);
        //将当前题目的id写到页面
        req.setAttribute("questionId",questionId);
        req.getRequestDispatcher("/WEB-INF/pages/store/questionItem/list.jsp").forward(req,resp);
    }


    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, FileUploadException {
        String id = req.getParameter("id");
        QuestionItem questionItem = questionItemService.findById(id);
        req.setAttribute("questionItem",questionItem);
        list(req,resp,null);
    }
    /**
     * 添加或者删除
     * @param req 添加时： req对象必须包含题目的id  修改时req必须包含题目id和选项id
     */
    private void saveOrEdit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //创建磁盘工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //Servlet文件上传核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //从request中读取数据
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        //数据部分，放入实体类
        QuestionItem questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);
        //根据getQuestionId获取路径
        String path = filePath+uploadPath+questionItem.getQuestionId();
        //拿到文件内容，并获取文件名部分
        String returnName = FileUtil.uploadFile(path, UUID.randomUUID().toString(), fileItems);
        //将文件名写入实体类
        if (StringUtils.isNoneBlank(returnName)){
            questionItem.setPicture(uploadPath+questionItem.getQuestionId()+"/"+returnName);
        }
        //questionItem=questionItemService.saveOrEdit(fileItems,path);
        //拿到选项id
        String id = questionItem.getId();
        //如果选项id为空 就是保存操作
        if (StringUtils.isBlank(id)){ //保存
            questionItemService.save(questionItem);
        }else {//否则就是修改操作修改
            questionItemService.update(questionItem);
        }
        list(req,resp,questionItem.getQuestionId());
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, FileUploadException {
        //拿到选项id 用于删除
        String id = req.getParameter("id");
        //在删除前判断是否有图片
        QuestionItem questionItem = questionItemService.findById(id);
        if (StringUtils.isNoneBlank(questionItem.getPicture())){
            new File(filePath,questionItem.getPicture()).delete();
        }
        //删除选项
        questionItemService.delete(questionItem);
        //往后传递
        list(req,resp,null);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
